package edu.gzhu.guli.core.repository.init;

import java.util.Arrays;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import edu.gzhu.guli.core.entity.Admin;
import edu.gzhu.guli.core.entity.Role;
import edu.gzhu.guli.core.repository.AdminRepository;
import edu.gzhu.guli.core.repository.RoleRepository;
import lombok.AllArgsConstructor;

@Component
@Order(1)
@AllArgsConstructor
public class AdminAndRoleDataSeed implements ApplicationRunner{

  private final RoleRepository roleRepository;
  private final AdminRepository adminRepository;
  private final PasswordEncoder encoder;

  @Override
  public void run(ApplicationArguments args) throws Exception {
    long count = roleRepository.count();
    if (count > 0) return;
    Role root = Role.builder().name("ROOT").description("系统管理员").build();
    Role admin = Role.builder().name("ADMIN").description("普通管理员").build();
    Role member = Role.builder().name("MEMBER").description("普通用户").build();
    roleRepository.saveAll(Arrays.asList(root, admin, member));

    Admin rootAdmin = new Admin();
    rootAdmin.setUsername("root");
    rootAdmin.setPassword(encoder.encode("123aa123bb"));
    rootAdmin.setName("系统管理员");
    rootAdmin.setRole(root);
    adminRepository.save(rootAdmin);
  }
  
}
